package com.ibeeking.found.msg.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IWxCpMsgTemplateService;
import com.ibeeking.found.msg.rest.service.IOpenService;
import com.ibeeking.found.msg.service.common.dos.WxCpMsgTemplateDO;

import com.ibeeking.found.msg.service.common.query.WxCpMsgTemplateQuery;
import com.ibeeking.found.msg.service.common.vo.WxCpMsgTemplateVO;

import com.ibeeking.found.msg.service.mapper.WxCpMsgTemplateMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import lombok.SneakyThrows;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName WxMpMsgTemplateServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-09-26 14:05
 **/
@Service
public class WxCpMsgTemplateServiceImpl implements IWxCpMsgTemplateService {

    @Resource
    private IOpenService wxOpenServiceImpl;

    @Resource
    private WxCpMsgTemplateMapper wxCpMsgTemplateMapper;

    @Override
    public List<WxCpMsgTemplateVO> list(WxCpMsgTemplateQuery query) {
        List<WxCpMsgTemplateDO> templateDOS = wxCpMsgTemplateMapper.selectList(new LambdaQueryWrapper<WxCpMsgTemplateDO>()
                .eq(query.getId() != null , WxCpMsgTemplateDO::getId, query.getId())
                .eq(StringUtils.isNotEmpty(query.getTemplateId()), WxCpMsgTemplateDO::getTemplateId, query.getTemplateId())
                .eq(StringUtils.isNotEmpty(query.getTitle()), WxCpMsgTemplateDO::getTitle, query.getTitle())
        );
        LogUtils.info("=====templateDOS:{}======", JsonUtils.toJsonStr(templateDOS));
        //todo 临时增加同步模板消息
        if (Collections3.isEmpty(templateDOS)) {
            getBean().syncWxCpMsgTemplateFromWx();
        }
        List<WxCpMsgTemplateVO> templateVOS = JsonUtils.jsonToList(templateDOS, WxCpMsgTemplateVO.class);
        return templateVOS;
    }

    @Override
    public String queryTemplateIdById(Long id) {
        WxCpMsgTemplateDO templateDO = wxCpMsgTemplateMapper.selectById(id);
        return null != templateDO ? templateDO.getTemplateId() : "";
    }

    @Override
    public WxCpMsgTemplateVO queryTemplateByCode(String code) {
        WxCpMsgTemplateDO templateDO = wxCpMsgTemplateMapper.selectOne(Wrappers.lambdaQuery(WxCpMsgTemplateDO.class).eq(WxCpMsgTemplateDO::getTemplateId, code));
        return JsonUtils.fromJson(templateDO, WxCpMsgTemplateVO.class);
    }

    @SneakyThrows
    @Override
    public Integer syncWxCpMsgTemplateFromWx() {
        Long tenantId = UserUtils.getTenantID();
        WxMpService wxMpService = wxOpenServiceImpl.getWxOpenMpService(tenantId);
        if (wxMpService == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        WxMpConfigStorage WxMpConfigStorage = wxMpService.getWxMpConfigStorage();
        if (WxMpConfigStorage == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        String appId = WxMpConfigStorage.getAppId();
        if(StringUtils.isEmpty(appId)){
            throw new BusinessException("无法获取公众号APPID，请检查是否绑定公众号！");
        }
        WxMpTemplateMsgService wxMpTemplateMsgService = wxMpService.getTemplateMsgService();
        if (wxMpTemplateMsgService == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        List<WxMpTemplate> templateList = wxMpTemplateMsgService.getAllPrivateTemplate();
        LogUtils.info("=====templateList:{}======", JsonUtils.toJsonStr(templateList));
        if (Collections3.isEmpty(templateList)) {
            wxCpMsgTemplateMapper.delete(null);
        } else {
            wxCpMsgTemplateMapper.delete(null);
            List<WxCpMsgTemplateDO> doos = JsonUtils.jsonToList(templateList, WxCpMsgTemplateDO.class);
            doos.stream().forEach(d->{
                d.setAppId(appId);
            });
            wxCpMsgTemplateMapper.insertBatchSomeColumn(doos);
        }
        return templateList.size();
    }

    private WxCpMsgTemplateServiceImpl getBean() {
        return SpringBeanUtil.getBean(WxCpMsgTemplateServiceImpl.class);
    }

}
